package com.doeis.uwork.bean;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Comparator;

import com.doeis.common.utils.StringUtils;


public class ComparatorRelation implements Comparator {

	private String fieldName;
	private Integer order;
	public ComparatorRelation(String fieldName,Integer order){
		this.fieldName = fieldName;
		this.order = order;
	}
	public int compare(Object arg0, Object arg1) {
		int flag = 0;
		Object relation0=null;
		Object relation1=null;
		if (order==1) {
			relation0 = arg0;
			relation1 = arg1;
		}else {
			relation1 = arg0;
			relation0 = arg1;
		}
		Object value0 = getMethod(relation0, fieldName);
		Object value1 = getMethod(relation1, fieldName);
		if(value0==null || value1 ==null){
			return flag;
		}
		if(value0 instanceof Double ){
			flag = ((Double)value0).compareTo((Double)value1);
		}else if(value0 instanceof Integer ){
			flag = ((Integer)value0).compareTo((Integer)value1);
		}else if(value0 instanceof Float ){
			flag = ((Float)value0).compareTo((Float)value1);
		}else if(value0 instanceof Timestamp ){
			flag = ((Timestamp)value0).compareTo((Timestamp)value1);
		}
		return flag;
	}
	
	private Object getMethod(Object clazz, String fieldName) {
		if(StringUtils.isBlank(fieldName)){
			return null ;
		}
		Object result = null;
		try {
			Class ownerClass = clazz.getClass();
			Field[] fields = ownerClass.getDeclaredFields();
			Class fieldType = null;
			for (Field field : fields) {
				if (fieldName.equals(field.getName())) {
					fieldType = field.getType();
					break;
				}
			}
			StringBuffer sb = new StringBuffer(fieldName);
			sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
			fieldName = "get"+sb.toString();
			Method method = ownerClass.getMethod(fieldName);
			if ("Double.class".equals(fieldType)) {
				result = (Double)method.invoke(clazz);
			}else if ("String.class".equals(fieldType)) {
				result = (String)method.invoke(clazz);
			}else if ("java.lang.String".equals(fieldType.getName())){
				result = (String)method.invoke(clazz);
			}else if("java.lang.Float".equals(fieldType.getName())){
				result = (Float)method.invoke(clazz);
			}else if("java.lang.Integer".equals(fieldType.getName())){
				result = (Integer)method.invoke(clazz);
			}else if("java.lang.Double".equals(fieldType.getName())){
				result = (Double)method.invoke(clazz);
			}else if("java.sql.Timestamp".equals(fieldType.getName())){
				result = (Timestamp)method.invoke(clazz);
			}
			
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return result;
	}
	

}
